﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule;

public partial class Customer_List : PageBase
{
  
    private OrgainzationManager orgManager = new OrgainzationManager();
    private Boolean ReadOnly = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        ReadOnly =Request.QueryString.ToString().ToUpper().IndexOf("READONLY") > -1;
        if (!IsPostBack)
        {
           
            DataBind();
            if (txtHidOrg.Value == "")
            {
                this.txtHidOrg.Value = OrgHidValue;
                this.txtOrg.Text = OrgShowValue;
                var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
                if (data.Rows.Count != 1)
                {
                    OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlUserList);
                }
                else
                {
                    Person person = new PersonManager().Load(MyStateManager.PersonID);
                    ddlUserList.Items.Add(new ListItem(person.Name, MyStateManager.UserID.ToString()));
                    ddlUserList.Items.Insert(0, new ListItem("--所有--", ""));
                }

            }
            InitForm();
            InitConditionByUrl();
            if (ReadOnly)
            {
                btnNew.Visible = false;
            }
        }
    }

    #region 数据绑定
    private void InitForm()
    {
        //绑定客户渠道
        DictionaryItemsManager dim = new DictionaryItemsManager();
        ddlChannel.DataTextField = "Name";
        ddlChannel.DataValueField = "DictionaryItemId";
        ddlChannel.DataSource = dim.GetItemList(DictionaryEnum.CustomerChannel, this.MyStateManager.DomainID);
        ddlChannel.DataBind();
        ddlChannel.Items.Insert(0, new ListItem(Resources.language.ddl_All, ""));

       

        dim = new DictionaryItemsManager();
        drpCustomerType.DataTextField = "Name";
        drpCustomerType.DataValueField = "DictionaryItemId";
        drpCustomerType.DataSource = dim.GetItemList(DictionaryEnum.CustomerClass, this.MyStateManager.DomainID);
        drpCustomerType.DataBind();
        drpCustomerType.Items.Insert(0, new ListItem(Resources.language.ddl_All, ""));

        //客户销量等级
        ddlCustomerLevel.DataSource = dim.GetItemList(DictionaryEnum.Store_Level, MyStateManager.DomainID);
        ddlCustomerLevel.DataTextField = "NAME";
        ddlCustomerLevel.DataValueField = "DictionaryItemId";
        ddlCustomerLevel.DataBind();
        ddlCustomerLevel.Items.Insert(0, new ListItem(Resources.language.ddl_Select, ""));

    }
    #endregion

    

    #region 绑定查询数据
    public void BindGrid()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(string.Format(" AND c.DOMAIN_ID={0} ", MyStateManager.DomainID));
        if (txtHidOrg.Value != string.Empty)
        {
            sb.Append(string.Format(" AND c.ORG_ID IN ({0})", txtHidOrg.Value));

        }

 
        if (txtCustomer.Text != string.Empty)
        {
            sb.Append(" AND (C.[CODE] LIKE '%" + txtCustomer.Text.Trim() + "%' or C.[NAME] LIKE '%" + txtCustomer.Text.Trim() + "%' or CI.[ADDRESS_LINE] like  '%" + txtCustomer.Text.Trim() + "%' "
                + " or  "
                + " CI.telephone LIKE '%" + txtCustomer.Text.Trim() + "%' or  CI.fax LIKE '%" + txtCustomer.Text.Trim() + "%') ");
        }

       

      
        if (ddlUserList.SelectedValue != "")
        {
            sb.Append(string.Format(" AND RC.USER_ID={0}", ddlUserList.SelectedValue));
        }

     
        if (ddlChannel.SelectedValue != string.Empty)
        {
            sb.Append(" AND LOCAL_LEVEL1_CODE =  '" + ddlChannel.SelectedValue + "'  ");
        }

        if (ddlCustomerLevel.SelectedValue != "")
        {
            sb.Append(string.Format(" AND LOCAL_LEVEL2_CODE='{0}'", ddlCustomerLevel.SelectedValue));
        }

        if (drpCustomerType.SelectedValue != string.Empty)
        {
            sb.Append(" AND CUST_CLASS_CODE =  '" + drpCustomerType.SelectedValue + "'  ");
        }

      

      

        DataSet ds = CustomerManager.SearchCustomer(sb.ToString(), "1", ddlValid.SelectedValue, 0 , int.MaxValue, false);
        if (ds != null && ds.Tables.Count > 0)
        {

            GridPager1.DataSource = ds.Tables[0];
            GridPager1.GridView = gvChannelType;
            GridPager1.BindData();
            GridPager1.Visible = gvChannelType.Rows.Count > 0;

           
        }
    }
    #endregion

   
    //查询
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

    public void GridViewToolbarUserControl1_OnGVTBSetColumnsButtonEvent(object sender, EventArgs e)
    {
        BindGrid();
    }
  
    /// <summary>
    /// 分页
    /// </summary>
    public void GridViewPageIndexChanged()
    {
        BindGrid();
    }

   

    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        ddlUserList.Items.Clear();

       

        //判断当前的人所在的部门是不是最小的一级org
        var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
        if (data.Rows.Count != 1)
        {
            //绑定所选部门下的所有业代
            ddlUserList.DataTextField = "CODENAME";
            ddlUserList.DataValueField = "ID";
            ddlUserList.DataSource = new UserManager().GetAllUsersForDDL(MyStateManager.DomainID, OrgHidValue);
            ddlUserList.DataBind();
            ddlUserList.Items.Insert(0, new ListItem("--所有--", ""));
        }
        else
        {
            Person person = new PersonManager().Load(MyStateManager.PersonID);
            ddlUserList.Items.Add(new ListItem(person.Name, MyStateManager.UserID.ToString()));
        }
        

       
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        //string org = txtHidOrg.Value.Trim();
        //string customer = txtCustomer.Text.Trim();
        //string channel = ddlChannel.SelectedValue;
        //string valid = ddlValid.SelectedValue;
    
        //string status = "";

        //Response.Redirect(string.Format("../ExportExcel/ExportExcel.aspx?Org={0}&Customer={1}&Chain=&Channel={2}&Valid={3}&Status={5}&Store_Level={6}&Table={9}"
        //                                , org, customer, channel, valid,status,ddlStore_Level.SelectedValue,"Customers"));
        string org = txtHidOrg.Value.Trim();
        string customer = txtCustomer.Text.Trim();
        string channel = ddlChannel.SelectedValue;
        string village = "";
        string status = ddlValid.SelectedValue;

        Response.Redirect(string.Format("../ExportExcel/ExportExcel.aspx?Org={0}&Customer={1}&Chain=&Channel={2}&Valid={3}&Village={4}&Status={5}&StartDate={6}&EndDate={7}&Table={8}"
                                        , org, customer, channel, "1", village, status,"", "", "Customers_list"));
    }

    protected void InitConditionByUrl()
    {
        if (Request.QueryString.Count>0)
        {
        
            if (Request["customer"] != null)
                txtCustomer.Text = Request["customer"];
            if (Request["channel"] != null)
                ddlChannel.SelectedValue = Request["channel"];
          
            if (Request["userlist"] != null)
                ddlUserList.SelectedValue = Request["userlist"];
            if (Request["valid"] != null)
                ddlValid.SelectedValue = Request["valid"];

            
            BindGrid();
        }
    }

    public void PageIndexChanged(object sender, GridViewPageEventArgs e)
    {
        gvChannelType.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void gvChannelType_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string query = "";
        query += "?id=" + DataBinder.Eval(e.Row.DataItem, "ID");
       
        query += "&customer="+txtCustomer.Text;
        query += "&channel=" + ddlChannel.SelectedValue;
      
   
        query += "&userlist="+ddlUserList.SelectedValue;
        query += "&valid="+ddlValid.SelectedValue;
        query += "&PageIndex=" + gvChannelType.PageIndex.ToString();
        if (ReadOnly)
        {
            query += "&ReadOnly";
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink hl1 = (HyperLink)e.Row.FindControl("HyperLink1");
            HyperLink hl2 = (HyperLink)e.Row.FindControl("HyperLink2");
            if (hl1 != null)
            {
                hl1.NavigateUrl = "Customer_Maintain.aspx" + query;
            }
            if (hl2 != null)
            {
                hl2.NavigateUrl = "Customer_Maintain.aspx" + query;
            }
            
            e.Row.Cells[10].Text = DateTime.ParseExact(e.Row.Cells[10].Text, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture
                        , System.Globalization.DateTimeStyles.None).ToString("yyyy年MM月dd日 HH:mm:ss");
        }

    }
   
}
